package com.woniu.customer.configuration;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.woniu.common.entity.AdmCustomer;
import com.woniu.common.entity.AdmEmployee;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.UnsupportedEncodingException;

public class JWTCredentialsMatcher implements CredentialsMatcher {

	private final Logger log = LoggerFactory.getLogger(JWTCredentialsMatcher.class);

    @Override
    public boolean doCredentialsMatch(AuthenticationToken authenticationToken, AuthenticationInfo authenticationInfo) {
        //  从AuthenticationToken中获取用户提供的JWT令牌。
        String token = (String) authenticationToken.getCredentials();
        System.out.println("JWTMatchtoken:"+token);
        //  从AuthenticationInfo中获取存储的凭证
        Object stored = authenticationInfo.getCredentials();
        System.out.println("JWTMatchstored:"+stored);
        //  从AuthenticationInfo中获取盐值
        String salt = stored.toString();
        System.out.println("JWTMatchsalt:"+salt);

        //  获取用户信息
        AdmCustomer admCustomer = (AdmCustomer) authenticationInfo.getPrincipals().getPrimaryPrincipal();
        try {
            //  使用盐值对JWT令牌进行验证
            Algorithm algorithm = Algorithm.HMAC256(salt);
            JWTVerifier verifier = JWT.require(algorithm)
                    .withClaim("username", admCustomer.getEmail())
                    .build();
            verifier.verify(token);
            return true;
        } catch (UnsupportedEncodingException | JWTVerificationException e) {
            log.error("Token Error:{}", e.getMessage());
        }

        return false;
    }

}
